<template>
    <div style="width: 100%; height: 100%;">
        <div>
            <div class="align-stretch tree-panel">
                <org-tree :dept-list.sync="deptList" style="height: 100%;" @node-click="handleNodeClick" />
            </div>
            <div class=" app-container" style="margin-left: 270px;">
                <div class="pageTitle">
                    <div class="pageBtn" style="padding-left: 0;">
                        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
                    </div>
                </div>

                <page-main style="margin: 10px 10px 50px 0;">
                    <el-table ref="orderTable" v-loading="isLoading" class="actionTable" stripe :data="tableData"
                              header-cell-class-name="table-header" style="width: 100%;" border :row-class-name="tableRowClassName">
                        <el-table-column label="角色代码" width="130" prop="role_code" />
                        <el-table-column label="角色名称" width="130" prop="role_name" />
                        <el-table-column label="角色描述" prop="remark" />
<!--                        <el-table-column label="组织机构名称" width="130" prop="Expr1" />-->
                        <el-table-column label="操作" width="240" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" icon="el-icon-setting" @click="handleAdvanced(scope.row)">高级选项</el-button>
                                <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
                                <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </page-main>
            </div>
        </div>

        <el-dialog :title="currentRole.isNew?'添加角色':'修改角色'" :visible.sync="detailVisible" width="600px">
            <el-form ref="form" :model="currentRole" :rules="rules" label-width="120px" size="small">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="所属组织机构">
                            <treeselect v-model="currentRole.dept_id" disabled="true" :clearable="false" :normalizer="normalizer" :options="deptList" placeholder="选择上级部门" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="角色名称" prop="role_name">
                            <el-input v-model="currentRole.role_name" placeholder="请输入角色名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="角色代码" prop="index_code">
                            <el-input v-model="currentRole.role_code" placeholder="角色代码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="角色描述" prop="remark">
                            <el-input v-model="currentRole.remark" type="textarea" placeholder="请输入角色描述" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="角色权限">
                            <div style="height: 300px; width: 100%; overflow: auto; border: 1px solid #e5e5e5; border-radius: 3px;">
                                <el-tree
                                    ref="menu"
                                    class="tree-border"
                                    :data="menuTreeData"
                                    show-checkbox
                                    default-expand-all
                                    node-key="menu_id"
                                    empty-text="加载中，请稍候"
                                    :props="{children:'children',label: 'menuName'}" />
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="detailVisible = false">取 消</el-button>
                <el-button size="small" :loading="isLoading" type="primary" @click="handleSubmit">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="'高级选项 【'+currentRole.role_name+'】'" :visible.sync="advancedVisible" width="700px">
            <el-form ref="form" :model="currentRole" label-position="top" :rules="rules" label-width="120px" size="small">
                <el-row :gutter="15">
                    <el-col :span="12">
                        <el-form-item label="资源权限" style="border: 1px solid #e5e5e5; padding-left: 10px; padding-right: 10px;">
                            <div style="height: 300px; width: 100%; overflow: auto; border-top: 1px solid #e5e5e5; padding-top: 5px;">
                                <el-tree
                                    class="tree-border resource-tree"
                                    :data="roleMenuTreeData"
                                    default-expand-all
                                    node-key="menu_id"
                                    :expand-on-click-node="false"
                                    :highlight-current="true"
                                    empty-text="加载中，请稍候"
                                    :props="{children:'children',label: 'menuName'}"
                                    @node-click="handleMenuClick" />
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="组织权限" style="border: 1px solid #e5e5e5; padding-left: 10px; padding-right: 10px;">
                            <div style="height: 300px; width: 100%; overflow: auto; border-top: 1px solid #e5e5e5; padding-top: 5px;">
                                <el-tree
                                    v-if="currentMenu"
                                    ref="deptTree"
                                    class="tree-border"
                                    :data="deptListForRole"
                                    show-checkbox
                                    default-expand-all
                                    :expand-on-click-node="false"
                                    node-key="dept_id"
                                    empty-text="加载中，请稍候"
                                    :props="{children:'children',label: 'dept_name'}" />
                                <div v-else class="flex align-center justify-center" style="height: 290px; width: 100%; overflow: auto;">
                                    选择左侧资源进行设置
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="advancedVisible = false">关 闭</el-button>
                <el-button size="small" :disabled="!currentMenu" :loading="isLoading" type="primary" @click="handleSaveAdvanced">保存并继续</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment';
import OrgTree from './OrgTree';
import {dictFilter} from '@/modules/components/DictSelect/dict-data';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { handleTree, deepClone } from '@/util';

import {
    InsertRole, UpdateRole,
    DeleteRole, AdvancedOptionsSettings, SelectAllRole, LoadAllMenu
} from '@/api/userManageApi';
import {getRouters} from '@/api/resourceApi';

export default {
    name: 'role-manage',
    components: {
        OrgTree, Treeselect
    },
    filters: {
        formatStatus(value) {
            return dictFilter(value, 'dict_UserStatus');
        }
    },
    props: {},
    data() {
        return {
            isLoading: false,
            tableData: [],
            detailVisible: false,
            advancedVisible: false,
            currentRole: {},
            rules: {
                role_code: [
                    { required: true, message: '角色代码不能为空', trigger: 'change' }
                ],
                role_name: [
                    { required: true, message: '角色名称不能为空', trigger: 'change' }
                ]
            },
            deptList: [],
            currentNode: null,
            menuTreeData: [],
            roleMenuTreeData: [],
            currentMenu: null
        };
    },
    computed: {
        deptListForRole() {
            let list = deepClone(this.deptList);
            return list;
        }
    },

    watch: {

    },
    created() {

    },
    mounted() {
        this.loadRemoteData();
        this.loadAllMenu();
    },
    methods: {
        moment,
        tableRowClassName({row, rowIndex}) {
            if ((this.detailVisible || this.advancedVisible)  && this.currentRole.role_id == row.role_id) {
                return 'selected-row';
            }
            return '';
        },
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                isDefaultExpanded: true,
                id: node.dept_id,
                label: node.dept_name,
                children: node.children
            };
        },
        handleNodeClick(data) {
            this.currentNode = data;
            this.loadRemoteData();
        },
        loadRemoteData() {
            this.isLoading = true;
            let params = this.currentNode &&  {dept_id: this.currentNode.dept_id};
            SelectAllRole(params).then(res => {
                this.isLoading = false;
                let result = res.res.SelectAllRole;
                this.tableData = result;
                console.log("tabledate——test--------------");
                console.log(this.tableData);
            }).catch(err => {
                this.isLoading = false;
                console.log(err);
            });
        },
        loadAllMenu() {
            LoadAllMenu().then(res => {
                let result = res.res.Menu;
                result[0].pid = 0;
                result[0].parentId = 0;
                console.log("查看result数据——------------------------");
                console.log(result);
                this.menuTreeData = handleTree(result, 'menu_id', 'parentId', 'children', 0);
                // this.menuTreeData = handleTree(result, 'id', 'pid', 'children', 0);
                console.log("查看menu树数据---------------");
                console.log(this.menuTreeData);
            }).catch(err => {
                console.log(err);
            });
        },
        handleAdd() {
            this.currentRole = {
                isNew: true,
                remark: '',
                dept_id: this.currentNode ? this.currentNode.dept_id : undefined,
                order_idx: 0,
                operator_id:0,
                gmt_create: null,
                gmt_modified:null,
                gmt_expire:null

            };
            this.detailVisible = true;
            this.$nextTick(() => {
                this.$refs['form'] && this.$refs['form'].clearValidate();
                this.$refs['menu'] && this.$refs['menu'].setCheckedKeys([]);
            });

        },
        handleAdvanced(item) {
            this.currentRole = item;
            this.currentMenu = null;
            getRouters({
                role_id: item.role_id
            }).then(res => {
                let result = res.res.Menu;
                result.unshift({
                    menu_id: 1,
                    parentId: 0,
                    menuName: '科技治超'
                });
                this.roleMenuTreeData = handleTree(result, 'menu_id', 'parentId', 'children', 0);
                // this.roleMenuTreeData = handleTree(result, 'id', 'pid', 'children', 0);
                console.log("查看rolemenuTreeData");
                console.log(this.roleMenuTreeData);
            }).catch(err => {
                console.log(err);
            });

            this.advancedVisible = true;
        },
        handleMenuClick(data) {
            console.log("点击节点查看资源权限data");
            console.log(data);
            this.currentMenu = data;
            if (data.deptId) {
                let arr = data.deptId.split(',');
                this.$nextTick(() => {
                    this.$refs['deptTree'] && this.$refs['deptTree'].setCheckedKeys(arr);
                });
            } else {
                this.$nextTick(() => {
                    this.$refs['deptTree'] && this.$refs['deptTree'].setCheckedKeys([]);
                });

            }
        },
        handleSaveAdvanced() {
            if (this.clickTooFast()) return;
            if (!this.currentMenu) {
                this.$message.warnings('请选择资源进行设置');
                return;
            }

            let array = this.$refs['deptTree'].getCheckedKeys(true);
            // console.log("查看array");
            // console.log(array);
            this.isLoading = true;
            AdvancedOptionsSettings({
                role_id: this.currentRole.role_id,
                menu_id: this.currentMenu.id,
                dept_ids: array.join(',')
            }).then(res => {
                this.isLoading = false;
                this.$message.success('保存成功');

                this.currentMenu.deptId = array.join(',');

            }).catch(err => {
                this.isLoading = false;
                console.log(err);
            });
        },
        handleEdit(item) {
            this.currentRole = {
                dept_id: item.dept_id,
                remark: item.remark,
                role_name: item.name,
                role_id: item.role_id,
                role_code: item.role_code
            };

            let menus = item.menu_id ? item.menu_id.split(',') : [];
            this.detailVisible = true;
            this.$nextTick(() => {
                this.$refs['form'] && this.$refs['form'].clearValidate();
                this.$refs['menu'] && this.$refs['menu'].setCheckedKeys(menus);
            });

        },
        handleDelete(item) {
            this.$confirm('确定要删除此角色吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.isLoading = true;
                DeleteRole({
                    role_id: item.role_id
                }).then(res => {
                    this.isLoading = false;
                    this.$message.success('删除成功');
                    this.loadRemoteData();
                }).catch(err => {
                    this.isLoading = false;
                    console.log(err);
                });
            }).catch(err => {
                console.log(err);
            });
        },
        handleSubmit() {
            if (this.clickTooFast()) return;
            this.$refs['form'].validate(valid => {
                console.log(valid);
                if (valid) {

                    this.isLoading = true;

                    let array = this.$refs['menu'].getCheckedKeys();
                    this.currentRole.menu = array.join(',');
                    console.log("查看currentRole");
                    console.log(this.currentRole);
                    if (this.currentRole.isNew) {
                        InsertRole(this.currentRole).then(res => {
                            this.$message.success('添加成功');
                            this.loadRemoteData();
                            this.detailVisible = false;
                            this.isLoading = false;
                        }).catch(err => {
                            this.isLoading = false;
                            console.log(err);
                        });
                    } else {
                        UpdateRole(this.currentRole).then(res => {
                            this.$message.success('修改成功');
                            this.loadRemoteData();
                            this.detailVisible = false;
                            this.isLoading = false;
                        }).catch(err => {
                            this.isLoading = false;
                            console.log(err);
                        });
                    }
                }
            });
        }

    }
};
</script>

<style scoped>
/* /deep/ */

/* .resource-tree .is-current { */

/*    background-color: #a0cfff !important; */

/* } */
/deep/
.el-form--label-top .el-form-item__label {
    padding: 5px;
    font-weight: bold;
}
/deep/
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background-color: #415284;
    color: #fff;
}
.table-header {
    background-color: #f8f8f8 !important;
}
/deep/
.el-table td {
    padding: 5px 0 !important;
}
/deep/
.el-button--text {
    padding: 5px 0;
}
/deep/
.el-dialog__body {
    padding: 10px 20px;
}
/deep/
.el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #dcdfe6;
}
</style>

<style lang="scss" scoped>

.table-header {
    background-color: #f8f8f8 !important;
}
.el-table ::v-deep td {
    padding: 5px 0 !important;
}
.tree-panel {
    margin-left: var(--real-sidebar-width);
    height: calc(100% - 120px);
    position: fixed;
    z-index: 100;
    left: 0;
    width: 260px;
    padding-left: 5px;
    padding-top: 5px;
    background: #fbfbfb;
    border: 1px solid #e5e5e5;
    margin-right: 10px;
}
</style>
